from flask import Blueprint, request
from collections import defaultdict
from utilsapp.mysql_con import  db_delete, db_insert,db_list, db_update
from utilsapp.mysql_con import db_pagelist,db_deletes
from utilsapp.common import assign_value, parsing_data_id, parsing_permissions
from utilsapp import utils
from datetime import datetime
txl = Blueprint('txl', __name__)

@txl.route('/user', methods=['POST'])
def user():
    id = assign_value(request.json, "id")
    type = assign_value(request.json,"type")
    page = assign_value(request.json,"page")
    size = assign_value(request.json,"size")
    sql = f"""select userinfo.* from userinfo
    LEFT JOIN role ON userinfo.role_id = role.id
    WHERE role.dataId = {parsing_permissions(request)['dataId']} and {'userinfo.' + type + '_id = ' + str(id) if id != -1 else '1 = 1'}
    ORDER BY id DESC"""

    total = len(db_list(sql)['data'])
    data = db_list(sql + f' LIMIT {max(0, (page - 1) * size)},{size}')['data']
    return utils.ok({'data': data, 'total': total})

@txl.route('/role', methods=['POST'])
def role():
    return db_list(f"""select * from role
    WHERE dataId = {parsing_permissions(request)['dataId']}
    ORDER BY id DESC""")

@txl.route('/department', methods=['POST'])
def department():
    return db_list(f"""select * from department
    WHERE pid = {parsing_permissions(request)['dataId']}
    ORDER BY id DESC""")

@txl.route('/addDepartment', methods=['POST'])
def addDepartment():
    request.json['pid'] = parsing_permissions(request)['dataId']
    return db_insert('department', request.json)

@txl.route('/deleteDepartment', methods=["post"])
def deleteDepartment():
    id = request.json['id']
    return db_delete('department', f'WHERE id=%s', {'id': id})

@txl.route('/editUser', methods=["post"])
def editUser():
    id_ = assign_value(request.json, "id")
    keys_not_add = ['id']
    addModel = {key: request.json[key]
                    for key in request.json if key not in keys_not_add}
    return db_update('userinfo',addModel,f"where id =%s", {"id_": id_})